package Servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Time;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import DBOperation.DBOperation;

/**
 * Servlet implementation class GetFeedServlet
 */
@WebServlet("/GetFeedServlet")
public class GetFeedServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GetFeedServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		HttpSession session = request.getSession(true);
		int userid = (Integer)session.getAttribute("userid");
		String user = request.getParameter("user");
		ResultSet rs;
		DBOperation dbo = new DBOperation();
		
		if(user == "all")
			rs = dbo.getAllFeeds();
		else
			rs = dbo.getMyFeeds(userid);
		
		String feedJson = "";
		try {
			while(rs.next())
			{
				int fid = rs.getInt("fid");
				int userId = rs.getInt("userid");
				String userName = rs.getString("username");
				String content = rs.getString("content");
				String company = rs.getString("company");
				Timestamp timeStamp = rs.getTimestamp("gmt_modified");
				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String time = df.format(timeStamp);
				
				String[] arrKey = {"fid", "userid", "username", "content", "company", "gmt_modified"};
				String[] arrValue = {fid+"", userId+"", userName, content, company, time};
				feedJson += dbo.getJson(arrKey, arrValue) + ";";
			}
			
			feedJson = feedJson.substring(0, feedJson.length()-1);
			System.out.println("-feedJson-"+feedJson);
			response.setCharacterEncoding("UTF-8");
			PrintWriter out = response.getWriter();
			
			out.print(feedJson);
			out.flush();
			out.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
